<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <a-spin :spinning="isLoading">
      <a-form :form="form" @submit="handleSubmit">
        <a-card title="奖励条件" style="width: 300px" size="small">
          <p>
            <a-form-item>
              <div class="input-number-group">
                <span class="ant-input-group-wrapper">
                  <span class="ant-input-wrapper ant-input-group">
                    <span class="ant-input-group-addon">直推等级到</span>
                    <a-select
                      style="width: 128px"
                      v-decorator="[
                        'upgrade.referee_level',
                        { rules: [{ required: true, message: '请选择奖励条件' }] },
                      ]"
                    >
                      <a-select-option :value="item.grade_id" v-for="(item, i) in gradeData" :key="i">
                        {{ item.name }}
                      </a-select-option>
                    </a-select>
                  </span>
                </span>
              </div>
            </a-form-item>
            <a-form-item>
              <InputNumberGroup
                addonBefore="邀请直推满"
                addonAfter="人"
                :inputProps="{ min: 0, precision: 0 }"
                v-decorator="['upgrade.referee_num', { rules: [{ required: true, message: '直推满人不能为空' }] }]"
              />
            </a-form-item>
            <a-form-item>
              <InputNumberGroup
                addonBefore="消费次数满"
                addonAfter="双"
                :inputProps="{ min: 0, precision: 2 }"
                v-decorator="['upgrade.me_consume_num', { rules: [{ required: true, message: '消费次数不能为空' }] }]"
              />
            </a-form-item>
          </p>

          <div class="form-item-help">
            <p class="extra">直推指定数量的达标用户升级到了指定等级并且自己消费了指定数量才能获取管理员奖</p>
          </div>
        </a-card>
        <br />

        <a-card title="分润奖励" style="width: 300px" size="small">
          <p v-for="(item, i) in gradeData" :key="i">
            <a-form-item>
              <InputNumberGroup
                :key="i"
                :addonBefore="item.name"
                addonAfter="%"
                :inputProps="{ min: 0, precision: 2, max: 100 }"
                v-decorator="[`prize.${item.grade_id + '_'}`, { rules: [{ required: true, message: '数据不能为空' }] }]"
              />
            </a-form-item>
          </p>
          <div class="form-item-help">
            <p class="extra">按照百分比分润，例如：100元提成10%则获取利润（100*0.1）=10元</p>
          </div>
        </a-card>
        <a-form-item :wrapper-col="{ span: wrapperCol.span, offset: labelCol.span }">
          <a-button type="primary" html-type="submit">保存</a-button>
        </a-form-item>
      </a-form>
    </a-spin>
  </a-card>
</template>

<script>
import pick from 'lodash.pick'
import * as AdminPrizeApi from '@/api/user/adminPrize'
import * as gradeApi from '@/api/user/grade'
import { InputNumberGroup } from '@/components'
import { isEmpty } from '@/utils/util'

export default {
  components: {
    InputNumberGroup,
  },
  data() {
    return {
      record: {},
      // 标签布局属性
      labelCol: { span: 12 },
      // 输入框布局属性
      wrapperCol: { span: 12 },
      // loading状态
      isLoading: false,
      // 当前表单元素
      form: this.$form.createForm(this),
      // 单选框样式
      radioStyle: {
        display: 'block',
        height: '30px',
        lineHeight: '30px',
      },
      // 会员等级列表
      gradeData: [],
    }
  },
  // 初始化数据
  created() {
    //设置默认值
    this.getDetail()
  },
  methods: {
    // 获取当前详情数据
    getDetail() {
      this.isLoading = true
      AdminPrizeApi.detail({
        key: ['referee_level', 'referee_num', 'me_consume_num'],
      })
        .then((result) => {
          console.log(result.data.values)
          // 当前记录
          this.record['upgrade'] = result.data
          // 获取全部会员等级
          this.getGradeAll()
        })
        .finally((result) => {
          this.isLoading = false
        })
    },
    // 获取全部会员等级
    getGradeAll() {
      let pthis = this
      this.isLoading = true
      gradeApi
        .all({ status: 1 })
        .then((result) => {
          this.gradeData = result.data.list
          let prize = {}
          let levelMap = {}
          for (let index = 0; index < result.data.list.length; index++) {
            let item = result.data.list[index]
            let grade_id = item.grade_id
            prize[grade_id + '_'] = item.admin_prize
            levelMap[grade_id] = item.name
          }
          this.record['prize'] = prize
          this.record['upgrade']['referee_level'] = levelMap[this.record['upgrade']['referee_level']]
          // 设置默认值
          this.setFieldsValue()
        })
        .finally((result) => {
          this.isLoading = false
        })
    },

    /**
     * 设置默认值
     */
    setFieldsValue() {
      const { record, $nextTick, form } = this
      !isEmpty(form.getFieldsValue()) &&
        $nextTick(() => {
          form.setFieldsValue(pick(record, ['upgrade', 'prize']))
        })
    },

    /**
     * 确认按钮
     */
    handleSubmit(e) {
      e.preventDefault()
      // 表单验证
      const {
        form: { validateFields },
      } = this
      validateFields((errors, values) => {
        // 提交到后端api
        !errors && this.onFormSubmit(values)
      })
    },

    /**
     * 提交到后端api
     */
    onFormSubmit(values) {
      this.isLoading = true
      AdminPrizeApi.save(values)
        .then((result) => {
          // 显示提示信息
          this.$message.success(result.message, 1.5)
        })
        .finally((result) => {
          this.isLoading = false
        })
    },
  },
}
</script>
